﻿using System;
using System.ComponentModel;
using System.Collections;

namespace UtfprLibrary.EntityFramework.ComponentModel {
    /// <summary>
    /// Property descriptor that converts EntityCollection<T> properties into 
    /// EntityBindingList properties.
    /// </summary>
    class CollectionPropertyDescriptor : PropertyDescriptor {
        IEntityDataSource _ds;
        PropertyDescriptor _pd;
        Type _listType;

        public CollectionPropertyDescriptor(IEntityDataSource ds, PropertyDescriptor pd)
            : base(pd.Name, null) {
            _ds = ds;
            _pd = pd;
            var elementType = _pd.PropertyType.GetGenericArguments()[0];
            _listType = typeof(EntityBindingList<>);
            _listType = _listType.MakeGenericType(elementType);
        }

        public override string Name {
            get { return _pd.Name; }
        }

        public override bool IsReadOnly {
            get { return _pd.IsReadOnly; }
        }

        public override void ResetValue(object component) {
            _pd.ResetValue(component);
        }

        public override bool CanResetValue(object component) {
            return _pd.CanResetValue(component);
        }

        public override bool ShouldSerializeValue(object component) {
            return _pd.ShouldSerializeValue(component);
        }

        public override Type ComponentType {
            get { return _pd.ComponentType; }
        }

        public override Type PropertyType {
            get { return _listType; }
        }

        public override object GetValue(object component) {
            return Activator.CreateInstance(_listType, _ds, (IEnumerable)_pd.GetValue(component), Name);
        }

        public override void SetValue(object component, object value) {
            _pd.SetValue(component, value);
            OnValueChanged(component, EventArgs.Empty);
        }
    }
}
